//用户参数注册校验中间件
const { User } = require('../model')
const joi = require('joi')

module.exports.userValidate = async (ctx,next) => {
    const userScema = joi.object({
        username:joi.string().required(),
        password:joi.string().min(5).required(),
        email:joi.string().email().required(),
        phone:joi.required()
    }) //定义schema
    const userVail = userScema.validate(ctx.request.body) //参数校验
    if(userVail.error){
        ctx.body = {code:400,errMsg:userVail.error}
    }
    // 用户名 邮箱 手机号重复校验
    const {username,phone,email} = ctx.request.body
    const isExitUser = await User.findOne({username})
    if(isExitUser){
        ctx.body = {code:400,errMsg:'用户名已经存在!'}
        return
    }
    const isExitPhone = await User.findOne({phone})
    if(isExitPhone){
        ctx.body = {code:400,errMsg:'手机号已经存在!'}
        return
    }
    const isExitEmail = await User.findOne({email})
    if(isExitEmail){
        ctx.body = {code:400,errMsg:'邮箱已经存在!'}
        return
    }
     await next(); // ps:注意📢一定要有 await 等待next执行完
}